package com.androidwwf.jwr;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBQuiz{

	private final String KEY_ROWID = "_id";
	private final String KEY_QUESTION = "question";
	private final String KEY_ANSWERONE = "answerone";
	private final String KEY_ANSWERTWO = "answertwo";
	private final String KEY_ANSWERTHREE = "answerthree";
	private final String KEY_ANSWERFOUR = "answerfour";
	private final String KEY_CORRECTANSWER = "correctanswer";
	private final String KEY_POINTS = "points";

	private final String DATABASE_NAME = "androidwwf";
	private final String DATABASE_TABLE = "tblquiz";
	private final int DATABASE_VERSION = 1;

	private DbHelper ourHelper;
	private Context ourContext;
	private SQLiteDatabase ourDatabase;

	// Array amount needs to be around the half of the total amount of questions.
	private int[] lastquestions = new int[3];
	private int lastnumber = 0;

	public DBQuiz(Context c) {
		this.ourContext = c;
	}

	public DBQuiz open() {
		ourHelper = new DbHelper(ourContext);
		ourDatabase = ourHelper.getWritableDatabase();
		return this;
	}

	public void close() {
		ourHelper.close();
	}
	
	private int getMaxRecordsIntblQuiz() {
		Cursor cc = ourDatabase.query(DATABASE_TABLE,
				new String[] { KEY_ROWID }, null, null, null, null, null);
		int maxid = 0;
		cc.moveToFirst();
		for (cc.moveToFirst(); !cc.isAfterLast(); cc.moveToNext()) {
			maxid++;
		}
		cc.close();
		
		return maxid;
	}

	private int getNewRandomNumber() {
		int maxid = getMaxRecordsIntblQuiz();

		int result = 0;

		boolean correct = false;

		while (!correct) {
			result = (int) (maxid * Math.random()) + 1;
			if (checkLastQuestions(result)) {
				correct = true;
			}
		}

		if (lastnumber == lastquestions.length) {
			lastnumber = 0;
			lastquestions[lastnumber] = result;
			lastnumber++;
		} else {
			lastquestions[lastnumber] = result;
			lastnumber++;
		}

		return result;
	}

	private boolean checkLastQuestions(int number) {
		for (int i = 0; i < lastquestions.length; i++) {
			if (number == lastquestions[i]) {
				return false;
			}
		}
		return true;
	}

	/*
	 * Insert a new row into de tblquiz. You must provide a question and 4
	 * answer. The correct answer and the amount of points the question is
	 * worth. When giving the correctanswer, String answerone == 1, String
	 * answertwo == 2 etc. So if the answer to this question is the answer given
	 * at answer two, the int correct answer must be 2.
	 */
	public void createEntry(String question, String answerone,
			String answertwo, String answerthree, String answerfour,
			int correctanswer, int points) {

		ContentValues cv = new ContentValues();
		cv.put(KEY_QUESTION, question);
		cv.put(KEY_ANSWERONE, answerone);
		cv.put(KEY_ANSWERTWO, answertwo);
		cv.put(KEY_ANSWERTHREE, answerthree);
		cv.put(KEY_ANSWERFOUR, answerfour);
		cv.put(KEY_CORRECTANSWER, correctanswer);
		cv.put(KEY_POINTS, points);
		ourDatabase.insert(DATABASE_TABLE, null, cv);
	}

	public boolean checkIfEmpty()
	{
		open();
		Cursor c = ourDatabase.query(DATABASE_TABLE, new String[]{KEY_ROWID},
				KEY_ROWID + "= ?", new String[]{"1"}, null, null, null);
		
		if (c == null || c.getCount() == 0) {
			fillDatabase();
			c.close();
			close();
			
			return true;
		}
		else
		{
			c.close();
			close();
			
			return false;
		}
	}
	
	public String[] getNewQuestion() {

		open();
		
		String[] columns = new String[] { KEY_ROWID, KEY_QUESTION,
				KEY_ANSWERONE, KEY_ANSWERTWO, KEY_ANSWERTHREE, KEY_ANSWERFOUR,
				KEY_CORRECTANSWER, KEY_POINTS };

		int newnumber = getNewRandomNumber();
		String[] id = { String.valueOf(newnumber) };

		Cursor c = ourDatabase.query(DATABASE_TABLE, columns,
				KEY_ROWID + "= ?", id, null, null, null);
		
		int row = c.getColumnIndex(KEY_ROWID);
		int question = c.getColumnIndex(KEY_QUESTION);
		int answerone = c.getColumnIndex(KEY_ANSWERONE);
		int answertwo = c.getColumnIndex(KEY_ANSWERTWO);
		int answerthree = c.getColumnIndex(KEY_ANSWERTHREE);
		int answerfour = c.getColumnIndex(KEY_ANSWERFOUR);
		int correctanswer = c.getColumnIndex(KEY_CORRECTANSWER);
		int points = c.getColumnIndex(KEY_POINTS);

		c.moveToFirst();
		String strow = c.getString(row);
		String stquestion = c.getString(question);
		String stanswerone = c.getString(answerone);
		String stanswertwo = c.getString(answertwo);
		String stanswerthree = c.getString(answerthree);
		String stanswerfour = c.getString(answerfour);
		String stcorrectanswer = c.getString(correctanswer);
		String stpoints = c.getString(points);
		
		c.close();
		close();
		String[] result = new String[] { strow, stquestion, stanswerone,
				stanswertwo, stanswerthree, stanswerfour, stcorrectanswer,
				stpoints };

		return result;
	}

	private void fillDatabase()
	{
		DBQuizStorage qs = new DBQuizStorage();
		
		int i = 1;
		
		while(qs.getQuestions(i) != null)
		{
			String[] question = new String[7];
			question = qs.getQuestions(i);
			open();
			createEntry(question[0], question[1], question[2], question[3], question[4], Integer.parseInt(question[5]), Integer.parseInt(question[6]));
			close();
			i++;
		}
	}
	
	private class DbHelper extends SQLiteOpenHelper {

		public DbHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ROWID
					+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_QUESTION
					+ " TEXT, " + KEY_ANSWERONE + " TEXT, " + KEY_ANSWERTWO
					+ " TEXT, " + KEY_ANSWERTHREE + " TEXT, " + KEY_ANSWERFOUR
					+ " TEXT, " + KEY_CORRECTANSWER + " INTEGER, " + KEY_POINTS
					+ " INTEGER );");
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
			onCreate(db);
		}
	}
}
